import React, { Component } from "react";
import {
  Form,
  Input,
  Table,
  Divider,
  Button,
  Modal,
  DatePicker,
  Row,
  Col,
  Select,
  Popconfirm
} from "antd";
import Content from "../../components/Content/Content";
import moment from "moment";

const { Item } = Form;
const { TextArea } = Input;
const { RangePicker } = DatePicker;
const { Option } = Select;
const { confirm } = Modal;

//表格内容数据
const data = [];
for (let i = 0; i < 6; i++) {
  data.push({
    id: i,
    m_id: `AACC000${i}`,
    m_name: `${i}`,
    m_jj: `2019/9/${i}`
  });
}

class Query_mediumForm extends Component {
  state = {
    dataSource: data,
    count: 0,

    loading: false,
    editData: {},
    searchParams: {},

    filteredInfo: null,
    sortedInfo: null,

    showEditModal: false
  };

  loadData = (current = 1) => {

    this.setState({ loading: true });
    // ajax request after empty completing
    setTimeout(() => {
      this.setState({
        loading: false
      });
    }, 1000);

    const url = global.api.managementAdd
    + "?m_id=" + (this.state.searchParams.m_id || "")
    + "&m_name=" + (this.state.searchParams.m_name || "")
    + "&m_jj=" + (this.state.searchParams.m_jj || "")
    + "&m_sxbd=" + (this.state.searchParams.m_sxbd || "")
    + "&m_type=" + (this.state.searchParams.m_type || "")
    + "&m_time=" + (this.state.searchParams.m_time || "")
    + "&m_person=" + (this.state.searchParams.m_person || "");
    return global.getdata.get(url, {page_index: current, page_size: this.state.pageSize, search: {}})
    .then(res => {
      this.setState({dataSource: res.results, count: res.count})
    })
    .catch(err => {
      
    }) 

  }

  componentDidMount() {
    this.loadData(1);
  }

  // 删除
  handleDelete = (id) => {
    const dataSource = [...this.state.dataSource];

    const url = global.api.managementAdd + id + '/';
    return global.deletedata.del(url, {})
    .then(res => {  
      // this.setState({ dataSource: dataSource.filter(item => item.id !== id)});
      this.loadData(1)
      Modal.success({
        content: '删除成功!',
      });
    })
    .catch(err => {
      Modal.error({
        content: '删除出错!',
      });
    })    
  }

  // 更新
  handleUpdate = () => {
    const url = global.api.managementAdd + this.state.editData.id + '/';
    return global.updatedata.put(url, this.state.editData)
    .then(res => {  
      this.loadData(1);
      Modal.success({
        content: '更新成功!',
      });
    })
    .catch(err => {
      Modal.error({
        content: '更新出错!',
      });
    })    
  }

  handleChange = (pagination, filters, sorter) => {
    console.log("Various parameters", pagination, filters, sorter);
    this.setState({
      filteredInfo: filters,
      sortedInfo: sorter
    });
  };

  onSelectChange = selectedRowKeys => {
    console.log("selectedRowKeys changed: ", selectedRowKeys);
    this.setState({ selectedRowKeys });
  };

  //Modal
  showEditModal(showEditModal, record = {}) {
    this.setState({ showEditModal: showEditModal, editData: record });
  }

  render() {
    //全部选中/取消全选
    const { selectedRowKeys } = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
      hideDefaultSelections: true,
      selections: [
        {
          key: "allData",
          text: "全部选中",
          onSelect: () => {
            this.setState({
              selectedRowKeys: [...Array(this.state.count).keys()] // 0...29
            });
          }
        },
        {
          key: "nullData",
          text: "取消全选",
          onSelect: changableRowKeys => {
            let newSelectedRowKeys = [];
            newSelectedRowKeys = changableRowKeys.filter((key, index) => {
              return false;
            });
            this.setState({ selectedRowKeys: newSelectedRowKeys });
          }
        }
      ]
    };

    let { sortedInfo, filteredInfo } = this.state;
    sortedInfo = sortedInfo || {};
    filteredInfo = filteredInfo || {};
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 12 },
        sm: { span: 3 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 }
      }
    };
    const formItemLayoutt = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 }
      }
    };
    //表格表头数据
    const columns = [
      {
        title: "ID",
        key: "id",
        dataIndex: "id"
      },      
      {
        title: "筛选方法编号",
        key: "m_id",
        dataIndex: "m_id"
      },
      {
        title: "筛选方法名称",
        key: "m_name",
        dataIndex: "m_name  "
      },
      {
        title: "筛选方法简介",
        key: "m_jj",
        dataIndex: "m_jj"
      },
      {
        title: "筛选靶点",
        key: "m_sxbd",
        dataIndex: "m_sxbd"
      },
      {
        title: "药理活性类型",
        key: "m_type",
        dataIndex: "m_type"
      },

      {
        title: "创建时间",
        key: "m_time",
        dataIndex: "m_time",
        sorter: (a, b) =>
          a.date.replace(/[^\d.]/g, "") - b.date.replace(/[^\d.]/g, ""),
        sortOrder: sortedInfo.columnKey === "m_time" && sortedInfo.order
      },
      {
        title: "创建者",
        key: "m_person",
        dataIndex: "m_person"
      },
      {
        title: "操作",
        dataIndex: "caozuo",
        render: (text, record) => (
          <span>
            <Button type="dashed" onClick={() => this.showEditModal(true, record)}>
              修改
            </Button>
            <Divider type="vertical" />
            <Popconfirm title="确认删除吗?" onConfirm={() => this.handleDelete(record.id)}>
                <Button type="dashed" >删除</Button>
            </Popconfirm>
          </span>
        )
      }
    ];

    return (
      <div>
        <Form
          {...formItemLayout}
          onSubmit={this.onSubmit}
          colon={false}
          style={{ borderBottom: "20px solid #f0f2f5" }}
        >
          <Item label="筛选方法编号">
            <Input onChange={e => this.state.searchParams.m_id  = e.target.value } />
          </Item>
          <Item label="筛选方法名称">
            <Input onChange={e => this.state.searchParams.m_name  = e.target.value } />
          </Item>
          <Item label="筛选方法简介">
            <Input onChange={e => this.state.searchParams.m_jj  = e.target.value } />
          </Item>
          <Item label="筛选靶点">
            <Input onChange={e => this.state.searchParams.m_sxbd  = e.target.value } />
          </Item>
          <Item label="药理活性类型">
            <Select
              mode="tags"
              onChange={value => this.state.searchParams.m_type  = value[0]}
              style={{ width: "100%" }}
              tokenSeparators={[","]}
              showArrow={true}
            >
              <Option value="kxjhx">抗细菌活性</Option>
              <Option value="kzjhx">抗真菌活性</Option>
              <Option value="kbdhx">抗病毒活性</Option>
            </Select>
          </Item>
          <Item label="创建时间">
            <RangePicker
              onChange={(value, dateString) => this.state.searchParams.m_time = dateString}
              dateRender={current => {
                const style = {};
                if (current.date() === 1) {
                  style.border = "1px solid #1890ff";
                  style.borderRadius = "50%";
                }
                return (
                  <div className="ant-calendar-date" style={style}>
                    {current.date()}
                  </div>
                );
              }}
            />
          </Item>
          <Item label="创建者">
            <Input onChange={e => this.state.searchParams.m_person  = e.target.value } />
          </Item>
          <Item wrapperCol={{ span: 10, offset: 3 }}>
            <Row guuter={16}>
              <Col span={5}>
                <Button type="primary" htmlType="submit"onClick={()=>this.loadData(1)} loading={this.state.loading}>
                  查询
                </Button>
              </Col>
            </Row>
          </Item>
        </Form>

        <div>
          <Modal
            title=" 修改 "
            centered
            visible={this.state.showEditModal}
            onOk={() => this.showEditModal(false)}
            onCancel={() => this.showEditModal(false)}
            maskClosable={false}
          >
            <Form {...formItemLayoutt} onSubmit={this.onSubmit} colon={false}>
              <Item label="筛选方法编号">
                <Input defaultValue={this.state.editData.m_id} onChange={e => this.state.editData.m_id  = e.target.value } />
              </Item>
              <Item label="筛选方法名称">
                <Input defaultValue={this.state.editData.m_name} onChange={e => this.state.editData.m_name  = e.target.value } />
              </Item>
              <Item label="筛选方法简介">
                <TextArea autoSize={{ minRows: 3 }} defaultValue={this.state.editData.m_jj} onChange={e => this.state.editData.m_jj  = e.target.value } />
              </Item>
              <Item label="筛选靶点">
                <Input defaultValue={this.state.editData.m_sxbd} onChange={e => this.state.editData.m_sxbd  = e.target.value } />
              </Item>
              <Item label="药理活性类型">
                <Select
                  mode="tags"
                  style={{ width: "100%" }}
                  defaultValue={this.state.editData.m_type}
                  onChange={value => this.state.editData.m_type  = value[0]}
                  tokenSeparators={[","]}
                  showArrow={true}
                >
                <Option value="kxjhx">抗细菌活性</Option>
                <Option value="kzjhx">抗真菌活性</Option>
                <Option value="kbdhx">抗病毒活性</Option>
                </Select>
              </Item>
              <Item label="创建时间" wrapperCol>
                <DatePicker
                  defaultValue={moment(this.state.editData.m_time)}
                  onChange={(value, dateString) => this.state.editData.m_time = dateString}
                  style={{ width: "100%" }}
                  dateRender={current => {
                    const style = {};
                    if (current.date() === 1) {
                      style.border = "1px solid #1890ff";
                      style.borderRadius = "50%";
                    }
                    return (
                      <div className="ant-calendar-date" style={style}>
                        {current.date()}
                      </div>
                    );
                  }}
                />
              </Item>
              <Item label="创建者">
                <Input defaultValue={this.state.editData.m_person} onChange={e => this.state.editData.m_person = e.target.value } />
              </Item>

              <Item label="&nbsp;">
                <Button type="primary" htmlType="submit"onClick={()=>this.handleUpdate()} loading={this.state.loading}>
                  更新
                </Button>
              </Item>
              
            </Form>
          </Modal>
        </div>
        <Table
          rowSelection={rowSelection}
          bordered={true}
          columns={columns}
          dataSource={this.state.dataSource}
          onChange={this.handleChange}
        />
      </div>
    );
  }
}
const WrapperedQuery_mediumForm = Form.create({
  name: "query medium"
})(Query_mediumForm);

class ManageQuery extends Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  onSubmit = () => {
    const { form } = this.form.props;
    form.validateFields((errs, values) => {
      console.log(errs, values);
    });
  };
  render() {
    return (
      <Content>
        <WrapperedQuery_mediumForm
          wrappedComponentRef={ref => (this.form = ref)}
          onSubmit={this.onSubmit}
        />
      </Content>
    );
  }
}

export default ManageQuery;
